package com.rickpan.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import com.rickpan.service.MessageQueueService;
import com.rickpan.service.MessageRoutingService;
import com.rickpan.service.MessageRetryService;
import com.rickpan.service.TeamMessageProducer;
import com.rickpan.service.DeveloperAccessService;
import com.rickpan.socketio.TeamEventHandler;
import com.rickpan.dto.response.TeamMessageDTO;
import com.rickpan.utils.SecurityUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.List;
import java.util.ArrayList;

/**
 * RabbitMQ集成测试控制器
 * 提供测试接口用于验证RabbitMQ集成功能
 * 
 * @author 开发团队协调员
 * @since 2025-07-17
 */
@RestController
@RequestMapping("/api/test/rabbitmq")
public class RabbitMQTestController {

    private static final Logger logger = LoggerFactory.getLogger(RabbitMQTestController.class);

    @Autowired(required = false)
    private MessageQueueService messageQueueService;
    
    @Autowired(required = false)
    private MessageRoutingService messageRoutingService;
    
    @Autowired(required = false)
    private MessageRetryService messageRetryService;
    
    @Autowired(required = false)
    private TeamMessageProducer teamMessageProducer;

    @Autowired
    private TeamEventHandler teamEventHandler;

    @Autowired
    private DeveloperAccessService developerAccessService;

    private final ExecutorService testExecutor = Executors.newFixedThreadPool(10);

    // ==================== 权限验证 ====================

    /**
     * 验证开发者访问权限
     *
     * @param sessionToken 会话令牌
     * @return 是否有权限
     */
    private boolean validateDeveloperAccess(String sessionToken) {
        try {
            // 检查是否为管理员
            Long currentUserId = SecurityUtils.getCurrentUserId();
            boolean isAdmin = SecurityUtils.isAdmin();

            logger.info("🔍 开发者权限验证: userId={}, SecurityUtils.isAdmin()={}", currentUserId, isAdmin);

            if (!isAdmin) {
                logger.warn("🚫 非管理员尝试访问RabbitMQ测试工具: userId={}", currentUserId);
                return false;
            }

            // 验证开发者会话
            if (sessionToken == null || sessionToken.trim().isEmpty()) {
                logger.warn("🚫 缺少开发者会话令牌");
                return false;
            }

            Long userId = developerAccessService.validateSession(sessionToken);
            if (userId == null) {
                logger.warn("🚫 开发者会话无效或已过期: token={}", sessionToken.substring(0, 8) + "...");
                return false;
            }

            // 验证会话用户与当前用户是否一致
            if (!userId.equals(currentUserId)) {
                logger.warn("🚫 会话用户与当前用户不匹配: sessionUser={}, currentUser={}", userId, currentUserId);
                return false;
            }

            logger.info("✅ 开发者权限验证通过: userId={}", currentUserId);
            return true;

        } catch (Exception e) {
            logger.error("❌ 开发者权限验证异常", e);
            return false;
        }
    }

    /**
     * 创建权限验证失败的响应
     */
    private ResponseEntity<Map<String, Object>> createAccessDeniedResponse() {
        Map<String, Object> result = new HashMap<>();
        result.put("status", "error");
        result.put("error", "访问被拒绝：需要管理员权限和有效的开发者会话");
        result.put("code", "ACCESS_DENIED");
        return ResponseEntity.status(403).body(result);
    }

    // ==================== 基础功能测试 ====================

    /**
     * 简单的健康检查接口
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> health() {
        Map<String, Object> result = new HashMap<>();
        result.put("status", "ok");
        result.put("message", "RabbitMQ测试控制器正常运行");
        result.put("timestamp", System.currentTimeMillis());
        logger.info("🏥 健康检查请求");
        return ResponseEntity.ok(result);
    }

    /**
     * 测试RabbitMQ连接状态
     */
    @GetMapping("/connection-status")
    public ResponseEntity<Map<String, Object>> testConnectionStatus(
            @RequestHeader(value = "X-Developer-Session", required = false) String sessionToken) {

        // 验证开发者访问权限
        if (!validateDeveloperAccess(sessionToken)) {
            return createAccessDeniedResponse();
        }
        Map<String, Object> result = new HashMap<>();

        try {
            // 检查RabbitMQ是否可用
            boolean rabbitMQAvailable = false;
            String rabbitMQStatus = "未配置";

            if (teamEventHandler != null) {
                try {
                    rabbitMQAvailable = teamEventHandler.isRabbitMQAvailable();
                    rabbitMQStatus = rabbitMQAvailable ? "已连接" : "连接失败";
                } catch (Exception e) {
                    rabbitMQStatus = "检查失败: " + e.getMessage();
                }
            }

            // 检查各个服务组件
            result.put("rabbitmq_available", rabbitMQAvailable);
            result.put("rabbitmq_status", rabbitMQStatus);
            result.put("message_queue_service", messageQueueService != null);
            result.put("routing_service", messageRoutingService != null);
            result.put("retry_service", messageRetryService != null);
            result.put("producer_service", teamMessageProducer != null);

            // 计算整体状态
            if (rabbitMQAvailable && messageQueueService != null) {
                result.put("status", "success");
                result.put("message", "RabbitMQ服务正常");
            } else if (messageQueueService == null) {
                result.put("status", "warning");
                result.put("message", "RabbitMQ服务未启用（配置缺失）");
            } else {
                result.put("status", "error");
                result.put("message", "RabbitMQ服务异常");
            }

            logger.info("📊 RabbitMQ连接状态检查完成: available={}, status={}",
                       rabbitMQAvailable, result.get("status"));

        } catch (Exception e) {
            logger.error("❌ RabbitMQ连接状态检查失败", e);
            result.put("status", "error");
            result.put("message", "状态检查异常");
            result.put("error", e.getMessage());
            result.put("rabbitmq_available", false);
            result.put("rabbitmq_status", "检查异常");
            result.put("message_queue_service", false);
            result.put("routing_service", false);
            result.put("retry_service", false);
            result.put("producer_service", false);
        }

        return ResponseEntity.ok(result);
    }

    /**
     * 测试单条消息发送
     */
    @PostMapping("/send-message")
    public ResponseEntity<Map<String, Object>> testSendMessage(
            @RequestParam Long teamId,
            @RequestParam String content,
            @RequestParam(defaultValue = "text") String messageType) {

        Map<String, Object> result = new HashMap<>();

        // 检查RabbitMQ是否可用
        if (messageRoutingService == null && teamMessageProducer == null) {
            result.put("status", "error");
            result.put("error", "RabbitMQ服务未启用，无法进行消息发送测试");
            return ResponseEntity.ok(result);
        }

        try {
            // 创建测试消息
            TeamMessageDTO testMessage = new TeamMessageDTO();
            testMessage.setId(System.currentTimeMillis());
            testMessage.setTeamId(teamId);
            testMessage.setSenderId(1L); // 测试用户ID
            testMessage.setSenderName("测试用户");
            testMessage.setContent(content);
            testMessage.setMessageType(messageType);
            testMessage.setTimestamp(System.currentTimeMillis());
            testMessage.setMessageStatus("sending");

            // 通过路由服务发送
            if (messageRoutingService != null) {
                MessageRoutingService.MessageRoutingResult routingResult = 
                    messageRoutingService.routeTeamMessage(testMessage);
                
                result.put("routing_success", routingResult.isSuccess());
                result.put("routing_strategy", routingResult.getStrategy());
                result.put("is_duplicate", routingResult.isDuplicate());
                
                if (routingResult.getException() != null) {
                    result.put("routing_error", routingResult.getException().getMessage());
                }
            } else {
                // 直接通过生产者发送
                teamMessageProducer.sendTeamMessage(testMessage);
                result.put("routing_success", true);
                result.put("routing_strategy", "direct");
            }
            
            result.put("message_id", testMessage.getId());
            result.put("status", "success");
            
            logger.info("📤 测试消息发送完成: teamId={}, messageId={}", teamId, testMessage.getId());
            
        } catch (Exception e) {
            logger.error("❌ 测试消息发送失败: teamId={}", teamId, e);
            result.put("status", "error");
            result.put("error", e.getMessage());
        }
        
        return ResponseEntity.ok(result);
    }

    /**
     * 测试批量消息发送（高并发测试）
     */
    @PostMapping("/batch-send")
    public ResponseEntity<Map<String, Object>> testBatchSend(
            @RequestParam Long teamId,
            @RequestParam(defaultValue = "100") int messageCount,
            @RequestParam(defaultValue = "10") int concurrency) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<CompletableFuture<Void>> futures = new ArrayList<>();
            long startTime = System.currentTimeMillis();
            
            // 并发发送消息
            for (int i = 0; i < messageCount; i++) {
                final int messageIndex = i;
                
                CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                    try {
                        TeamMessageDTO testMessage = new TeamMessageDTO();
                        testMessage.setId(System.currentTimeMillis() + messageIndex);
                        testMessage.setTeamId(teamId);
                        testMessage.setSenderId(1L);
                        testMessage.setSenderName("批量测试用户");
                        testMessage.setContent("批量测试消息 #" + messageIndex);
                        testMessage.setMessageType("text");
                        testMessage.setTimestamp(System.currentTimeMillis());
                        testMessage.setMessageStatus("sending");

                        if (messageRoutingService != null) {
                            messageRoutingService.routeTeamMessage(testMessage);
                        } else {
                            teamMessageProducer.sendTeamMessage(testMessage);
                        }
                        
                    } catch (Exception e) {
                        logger.error("❌ 批量消息发送失败: index={}", messageIndex, e);
                    }
                }, testExecutor);
                
                futures.add(future);
                
                // 控制并发数
                if (futures.size() >= concurrency) {
                    CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
                    futures.clear();
                }
            }
            
            // 等待剩余任务完成
            if (!futures.isEmpty()) {
                CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
            }
            
            long endTime = System.currentTimeMillis();
            long duration = endTime - startTime;
            
            result.put("message_count", messageCount);
            result.put("concurrency", concurrency);
            result.put("duration_ms", duration);
            result.put("throughput_msg_per_sec", messageCount * 1000.0 / duration);
            result.put("status", "success");
            
            logger.info("📊 批量消息发送完成: count={}, duration={}ms, throughput={} msg/s", 
                       messageCount, duration, messageCount * 1000.0 / duration);
            
        } catch (Exception e) {
            logger.error("❌ 批量消息发送测试失败", e);
            result.put("status", "error");
            result.put("error", e.getMessage());
        }
        
        return ResponseEntity.ok(result);
    }

    // ==================== 统计和监控测试 ====================

    /**
     * 获取系统健康状态
     */
    @GetMapping("/health-status")
    public ResponseEntity<Map<String, Object>> getHealthStatus() {
        Map<String, Object> result = teamEventHandler.getSystemHealthStatus();
        
        // 添加队列特定的健康检查
        if (messageQueueService != null) {
            try {
                // 检查关键队列状态
                result.put("system_broadcast_queue_exists", 
                          messageQueueService.isQueueExists("system.broadcast"));
                result.put("file_upload_queue_exists", 
                          messageQueueService.isQueueExists("file.upload.progress"));
                result.put("dead_letter_queue_exists", 
                          messageQueueService.isQueueExists("message.dlq"));
                
            } catch (Exception e) {
                result.put("queue_check_error", e.getMessage());
            }
        }
        
        return ResponseEntity.ok(result);
    }

    /**
     * 获取路由统计信息
     */
    @GetMapping("/routing-stats")
    public ResponseEntity<Map<String, Object>> getRoutingStats() {
        Map<String, Object> result = new HashMap<>();
        
        if (messageRoutingService != null) {
            result.putAll(teamEventHandler.getMessageRoutingStats());
        } else {
            result.put("error", "路由服务不可用");
        }
        
        return ResponseEntity.ok(result);
    }

    /**
     * 获取重试统计信息
     */
    @GetMapping("/retry-stats")
    public ResponseEntity<Map<String, Object>> getRetryStats() {
        Map<String, Object> result = new HashMap<>();
        
        if (messageRetryService != null) {
            result.putAll(teamEventHandler.getMessageRetryStats());
        } else {
            result.put("error", "重试服务不可用");
        }
        
        return ResponseEntity.ok(result);
    }

    /**
     * 获取死信消息列表
     */
    @GetMapping("/dead-letters")
    public ResponseEntity<Map<String, Object>> getDeadLetters() {
        Map<String, Object> result = new HashMap<>();
        
        if (messageRetryService != null) {
            result.put("dead_letters", teamEventHandler.getDeadLetterMessages());
        } else {
            result.put("error", "重试服务不可用");
        }
        
        return ResponseEntity.ok(result);
    }

    /**
     * 重新处理死信消息
     */
    @PostMapping("/reprocess-dead-letter")
    public ResponseEntity<Map<String, Object>> reprocessDeadLetter(@RequestParam String messageKey) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            boolean success = teamEventHandler.reprocessDeadLetterMessage(messageKey);
            result.put("success", success);
            result.put("message_key", messageKey);
            result.put("status", success ? "success" : "failed");
            
            logger.info("🔄 死信消息重新处理: messageKey={}, success={}", messageKey, success);
            
        } catch (Exception e) {
            logger.error("❌ 死信消息重新处理失败: messageKey={}", messageKey, e);
            result.put("status", "error");
            result.put("error", e.getMessage());
        }
        
        return ResponseEntity.ok(result);
    }

    /**
     * 重置所有统计信息
     */
    @PostMapping("/reset-stats")
    public ResponseEntity<Map<String, Object>> resetStats() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            teamEventHandler.resetAllStats();
            result.put("status", "success");
            result.put("message", "所有统计信息已重置");
            
            logger.info("📊 统计信息重置完成");
            
        } catch (Exception e) {
            logger.error("❌ 统计信息重置失败", e);
            result.put("status", "error");
            result.put("error", e.getMessage());
        }
        
        return ResponseEntity.ok(result);
    }
}
